//
//  OneKeyLogin.m
//  Pods-Unity-iPhone
//
//  Created by MacPro on 2020/12/17.
//

#import "OneKeyLogin.h"
#import "OpenSDK_EventManager.h"
#import "OpenSDK_EventKeys.h"
#import "OpenSDK_DataKeys.h"
#import "OpenSDK_Toast.h"
#import "OpenSDK_UIUtil.h"
#import "OpenSDK_HttpUtil.h"
#import "OpenSDK_LoginManager.h"
#import "OpenSDK_DataManager.h"
#import "OpenSDK_UIManager.h"
#import "OpenSDK_Toast.h"
#import "JVERIFICATIONService.h"

@interface OneKeyLogin()
@property(nonatomic, assign)NSInteger preLoginStatus;   // -1：未知，0：成功，1：失败
@property(nonatomic, weak)UIViewController *parentViewController;

@property(nonatomic, strong) JVUIConfig *uiConfig;
@property(nonatomic, strong) JVAuthConfig *authConfig;

@end

@implementation OneKeyLogin

static NSString *APP_CONFIG=@"WcAppId";

- (NSString *)getServerName {
    return @"OneKey";
}

- (void)initInfo {
    [OpenSDK_EventManager addObsver:self selector:@selector(applicationDidFinishLaunching:) name:OPENSDK_EVENT_APPLICATION_DIDFINISHLAUNCHINGWITHOPTIONS object:nil className:@"OneKeyLogin"];
    [OpenSDK_EventManager addObsver:self selector:@selector(initSDK:) name:OPENSDK_EVENT_INIT object:nil className:@"OneKeyLogin"];
    _preLoginStatus = -1;
}

- (NSString *)getBackgroundImage {
    return @"op_login_type_pwd_bg";
}

- (NSString *)getDisplayIcon {
    return @"op_login_type_dy";
}

- (NSString *)getDisplayName {
    return @"一键登录";
}

-(NSString *) getDisplaySdkName {
    return @"一键登录";
}

- (NSString *)getPlatform {
    return @"OneKey";
}

- (NSString *)getPlatformVersion {
    return @"1.0";
}


- (NSInteger)status {
    return _preLoginStatus;
}

#pragma mark - OpenSDK初始化时，初始化微信
-(void) initSDK:(NSNotification*) notification {
    [self config];
    [JVERIFICATIONService preLogin:10000 completion:^(NSDictionary *result) {
        NSLog(@"一键登录预登陆结果：%@", result);
        long code = [result[@"code"] longValue];
        if (code == 7000) { // 成功
            self.preLoginStatus = 0;
        } else { // 失败
            self.preLoginStatus = 1;
        }
    }];
}

#pragma mark - 接口实现，调起登录
- (void)startLogin {
    if (self.preLoginStatus == -1) {    //
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self startLogin];
        });
    } else if (self.preLoginStatus == 0) { // 预取号成功，显示登录页面
        [self showLogin];
    } else {    // 预取号失败
        if (self.actionBlock) {
            self.actionBlock(19903, @"预取号失败");
        }
    }
}

- (void)showLogin {
    UIViewController *vc = [OpenSDK_UIUtil currentViewController];
    _parentViewController = vc;
    if (self.uiConfig) {
        BOOL contranctChecked = [OpenSDK_DataManager getInstance].contranctChecked;
        self.uiConfig.privacyState = contranctChecked;
        [self setCustomUiConfig:self.uiConfig];
    }
    
    [JVERIFICATIONService getAuthorizationWithController:vc hide:YES animated:NO timeout:15000 completion:^(NSDictionary *result) {
        NSLog(@"一键登录 Result: %@", result);
        long code = [result[@"code"] longValue];
        if (code == 6000) { // 登录成功
            NSString *loginToken = result[@"loginToken"];
            [OpenSDK_HttpUtil loginWithOneKeyToken:loginToken httpDelegate:self.loginDelegate];
        } else if (code == 6002) { // 取消登录
            if (self.actionBlock) {
                self.actionBlock(code, @"取消登录");
            }
        } else if (code == 6004) { // 正在登录
            if (self.actionBlock) {
                self.actionBlock(code, @"正在登录");
            }
        } else {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (self.loginDelegate) {
                    NSString *content = @"登录失败";
                    OpenSDK_BaseResData *resData = [[OpenSDK_BaseResData alloc] init];
                    [resData fail];
                    [resData setErrorMsg:content];
                    [resData setErrorNo:OpenSDK_SDK_LOGIN_FAILED];
                    self.loginDelegate(resData);
                }
            });
        }
    } actionBlock:self.actionBlock];
}


#pragma mark -

- (void)config {
    NSString *appKey = [[[[NSBundle mainBundle] infoDictionary] objectForKey:OpenSDK_CONFIG] objectForKey:OpenSDK_JAPP_KEY];
    NSParameterAssert(appKey);
    
    JVAuthConfig *config = [[JVAuthConfig alloc] init];
    config.appKey = appKey;
    config.channel = [OpenSDK_DataManager getInstance].channelID;
    config.timeout = 5000;
    config.isProduction = YES;
    config.authBlock = ^(NSDictionary *result) {
        NSLog(@"JAuth初始化结果：%@", result);
    };
    [JVERIFICATIONService setupWithConfig:config];
    self.authConfig = config;
    
    [self customUI];
}


- (void)customUI {
    JVUIConfig *config = [[JVUIConfig alloc] init];
    config.navCustom = YES;
    config.autoLayout = YES;
    config.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    config.dismissAnimationFlag = NO;
    
    // 弹框
    config.showWindow = YES;
    config.windowCornerRadius = 10;
    config.windowBackgroundAlpha = 0;
    
    CGFloat windowWidth = 390;
    CGFloat windowHeight = 228;
    JVLayoutConstraint *windowConstraintX = [JVLayoutConstraint constraintWithAttribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:JVLayoutItemSuper attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0];
    JVLayoutConstraint *windowConstraintY = [JVLayoutConstraint constraintWithAttribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:JVLayoutItemSuper attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0];
    JVLayoutConstraint *windowConstraintW = [JVLayoutConstraint constraintWithAttribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:JVLayoutItemNone attribute:NSLayoutAttributeWidth multiplier:1.0 constant:windowWidth];
    JVLayoutConstraint *windowConstraintH = [JVLayoutConstraint constraintWithAttribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:JVLayoutItemNone attribute:NSLayoutAttributeHeight multiplier:1.0 constant:windowHeight];
    config.windowConstraints = @[windowConstraintX, windowConstraintY, windowConstraintW, windowConstraintH];
    config.windowHorizontalConstraints = config.windowConstraints;
    
    // 如果指定logo图片，则设置对应logo图片
    NSString *logoImageName = [[[[NSBundle mainBundle] infoDictionary] objectForKey:OpenSDK_CONFIG] objectForKey:OpenSDK_LOGO];
    // 如果没有指定logo图片，则使用默认logo图片
    UIImage *image = [UIImage imageNamed:logoImageName];
    if (image != nil) {
        config.logoImg = image;
    } else {
        config.logoImg = [UIImage imageNamed:@"op_logo_yunchang"];
    }
    CGFloat logoWidth = 110;
    CGFloat logoHeight = 28;
    JVLayoutConstraint *logoConstraintX = [JVLayoutConstraint constraintWithAttribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:JVLayoutItemSuper attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0];
    JVLayoutConstraint *logoConstraintTop = [JVLayoutConstraint constraintWithAttribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:JVLayoutItemSuper attribute:NSLayoutAttributeTop multiplier:1.0 constant:30];
    JVLayoutConstraint *logoConstraintW = [JVLayoutConstraint constraintWithAttribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:JVLayoutItemNone attribute:NSLayoutAttributeWidth multiplier:1.0 constant:logoWidth];
    JVLayoutConstraint *logoConstraintH = [JVLayoutConstraint constraintWithAttribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:JVLayoutItemNone attribute:NSLayoutAttributeHeight multiplier:1.0 constant:logoHeight];
    config.logoConstraints = @[logoConstraintX, logoConstraintTop, logoConstraintW, logoConstraintH];
    config.logoHorizontalConstraints = config.logoConstraints;
    
    
    // 号码栏
    config.numberFont = [UIFont systemFontOfSize:22];
    config.numberColor = [UIColor colorWithRed:29.0/255.0 green:29.0/255.0  blue:29.0/255.0  alpha:1];
    JVLayoutConstraint *phoneConstraintX = [JVLayoutConstraint constraintWithAttribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:JVLayoutItemSuper attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0];
    JVLayoutConstraint *phoneConstraintTop = [JVLayoutConstraint constraintWithAttribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:JVLayoutItemSuper attribute:NSLayoutAttributeTop multiplier:1.0 constant:70];
    JVLayoutConstraint *phoneConstraintW = [JVLayoutConstraint constraintWithAttribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:JVLayoutItemNone attribute:NSLayoutAttributeWidth multiplier:1.0 constant:200];
    JVLayoutConstraint *phoneConstraintH = [JVLayoutConstraint constraintWithAttribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:JVLayoutItemNone attribute:NSLayoutAttributeHeight multiplier:1.0 constant:25];
    config.numberConstraints = @[phoneConstraintX, phoneConstraintTop, phoneConstraintW, phoneConstraintH];
    config.numberHorizontalConstraints = config.numberConstraints;
    
    // Slogan
    config.sloganTextColor = [UIColor lightGrayColor];
    config.sloganFont = [UIFont systemFontOfSize:10];
    JVLayoutConstraint *sloganConstraintX = [JVLayoutConstraint constraintWithAttribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:JVLayoutItemSuper attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0];
    JVLayoutConstraint *sloganConstraintTop = [JVLayoutConstraint constraintWithAttribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:JVLayoutItemNumber attribute:NSLayoutAttributeTop multiplier:1.0 constant:24];
    JVLayoutConstraint *sloganConstraintW = [JVLayoutConstraint constraintWithAttribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:JVLayoutItemNone attribute:NSLayoutAttributeWidth multiplier:1.0 constant:130];
    JVLayoutConstraint *sloganConstraintH = [JVLayoutConstraint constraintWithAttribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:JVLayoutItemNone attribute:NSLayoutAttributeHeight multiplier:1.0 constant:20];
    config.sloganConstraints = @[sloganConstraintX, sloganConstraintTop, sloganConstraintW, sloganConstraintH];
    config.sloganHorizontalConstraints = config.sloganConstraints;
    
    // 登录按钮
    UIImage *loginBtnImageNormal = [UIImage imageNamed:@"op_btn_base"];
    UIImage *loginBtnImageDisable = [UIImage imageNamed:@"op_btn_base"];
    UIImage *loginBtnImageHighlight = [UIImage imageNamed:@"op_btn_base"];
    config.logBtnImgs = @[loginBtnImageNormal, loginBtnImageDisable, loginBtnImageHighlight];
    config.logBtnFont = [UIFont systemFontOfSize:12];
    config.logBtnText = @"本机号码一键登录";
    JVLayoutConstraint *loginBtnConstraintX = [JVLayoutConstraint constraintWithAttribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:JVLayoutItemSuper attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0];
    JVLayoutConstraint *loginBtnConstraintTop = [JVLayoutConstraint constraintWithAttribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:JVLayoutItemSlogan attribute:NSLayoutAttributeTop multiplier:1.0 constant:32];
    JVLayoutConstraint *loginBtnConstraintW = [JVLayoutConstraint constraintWithAttribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:JVLayoutItemNone attribute:NSLayoutAttributeWidth multiplier:1.0 constant:246];
    JVLayoutConstraint *loginBtnConstraintH = [JVLayoutConstraint constraintWithAttribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:JVLayoutItemNone attribute:NSLayoutAttributeHeight multiplier:1.0 constant:24];
    config.logBtnConstraints = @[loginBtnConstraintX, loginBtnConstraintTop, loginBtnConstraintW, loginBtnConstraintH];
    config.logBtnHorizontalConstraints = config.logBtnConstraints;
    
    // 勾选框
    config.uncheckedImg = [UIImage imageNamed:@"op_ua_unselected"];
    config.checkedImg = [UIImage imageNamed:@"op_ua_selected"];
    JVLayoutConstraint *checkViewConstraintX = [JVLayoutConstraint constraintWithAttribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:JVLayoutItemSuper attribute:NSLayoutAttributeLeft multiplier:1.0 constant:72];
    JVLayoutConstraint *checkViewConstraintTop = [JVLayoutConstraint constraintWithAttribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:JVLayoutItemPrivacy attribute:NSLayoutAttributeTop multiplier:1.0 constant:0.5];
    JVLayoutConstraint *checkViewConstraintW = [JVLayoutConstraint constraintWithAttribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:JVLayoutItemNone attribute:NSLayoutAttributeWidth multiplier:1.0 constant:12];
    JVLayoutConstraint *checkViewConstraintH = [JVLayoutConstraint constraintWithAttribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:JVLayoutItemNone attribute:NSLayoutAttributeHeight multiplier:1.0 constant:12];
    config.checkViewConstraints = @[checkViewConstraintX, checkViewConstraintTop, checkViewConstraintW, checkViewConstraintH];
    config.checkViewHorizontalConstraints = config.checkViewConstraints;
    
    // 隐私
    config.privacyState = [OpenSDK_DataManager getInstance].contranctChecked;
    config.privacyTextAlignment = NSTextAlignmentLeft;
    config.privacyTextFontSize = 10;
    config.privacyComponents = @[@"我已详细阅读并同意", @"\n以及", @"和", @" "];
    NSString *contractWebUrl = [self simpleContractUrl:[OpenSDK_DataManager getInstance].contractWebUrl];
    if (contractWebUrl) {
        config.appPrivacyOne = @[@"用户协议", contractWebUrl];
    }
    NSString *privacyWebUrl = [self simpleContractUrl:[OpenSDK_DataManager getInstance].privacyWebUrl];
    if (privacyWebUrl) {
        config.appPrivacyTwo = @[@"隐私协议", privacyWebUrl];
    }
    config.privacyShowBookSymbol = true;
    config.appPrivacyColor = @[[UIColor lightGrayColor], [UIColor colorWithRed:74.0/225.0 green:169.0/255.0 blue:1 alpha:1]];
    // 协议导航栏
    config.agreementNavReturnImage = [UIImage imageNamed:@"op_ok_ag_back"];
    config.agreementNavBackgroundColor = [UIColor colorWithRed:74.0/225.0 green:169.0/255.0 blue:1 alpha:1];
    config.customPrivacyAlertViewBlock = ^(UIViewController *vc) {
        [[[OpenSDK_iToast makeText:@"请先同意相关政策条款再登录"] setDuration:2000] show];
    };
    
    JVLayoutConstraint *privacyConstraintX = [JVLayoutConstraint constraintWithAttribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:JVLayoutItemCheck attribute:NSLayoutAttributeRight multiplier:1.0 constant:5];
    JVLayoutConstraint *privacyConstraintX2 = [JVLayoutConstraint constraintWithAttribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:JVLayoutItemSuper attribute:NSLayoutAttributeRight multiplier:1.0 constant:-50];
    JVLayoutConstraint *privacyConstraintY = [JVLayoutConstraint constraintWithAttribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:JVLayoutItemSuper attribute:NSLayoutAttributeBottom multiplier:1.0 constant:-10];
    JVLayoutConstraint *privacyConstraintH = [JVLayoutConstraint constraintWithAttribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:JVLayoutItemNone attribute:NSLayoutAttributeHeight multiplier:1.0 constant:25];
    config.privacyConstraints = @[privacyConstraintX, privacyConstraintX2, privacyConstraintY, privacyConstraintH];
    config.privacyHorizontalConstraints = config.privacyConstraints;
    
    
    // loading
    JVLayoutConstraint *loadingConstraintX = [JVLayoutConstraint constraintWithAttribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:JVLayoutItemSuper attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0];
    JVLayoutConstraint *loadingConstraintY = [JVLayoutConstraint constraintWithAttribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:JVLayoutItemSuper attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0];
    JVLayoutConstraint *loadingConstraintW = [JVLayoutConstraint constraintWithAttribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:JVLayoutItemNone attribute:NSLayoutAttributeWidth multiplier:1.0 constant:30];
    JVLayoutConstraint *loadingConstraintH = [JVLayoutConstraint constraintWithAttribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:JVLayoutItemNone attribute:NSLayoutAttributeHeight multiplier:1.0 constant:30];
    config.loadingConstraints = @[loadingConstraintX, loadingConstraintY, loadingConstraintW, loadingConstraintH];
    config.loadingHorizontalConstraints = config.loadingConstraints;
    
    self.uiConfig = config;
    [self setCustomUiConfig:config];
}

- (void)setCustomUiConfig:(JVUIConfig *)uiConfig {
    CGFloat windowWidth = 390;
    [JVERIFICATIONService customUIWithConfig:uiConfig customViews:^(UIView *customAreaView) {
        //
        if (self.parentViewController.navigationController.viewControllers.count > 1) {
            UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(5, 10, 35, 35)];
            [backButton setImage:[UIImage imageNamed:@"op_btn_back"] forState:UIControlStateNormal];
            [backButton addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
            [customAreaView addSubview:backButton];
        } else {
            UIButton *closeButton = [[UIButton alloc] initWithFrame:CGRectMake(windowWidth - 35 - 5, 5, 35, 35)];
            [closeButton setImage:[UIImage imageNamed:@"op_btn_close"] forState:UIControlStateNormal];
            [closeButton addTarget:self action:@selector(close) forControlEvents:UIControlEventTouchUpInside];
            [customAreaView addSubview:closeButton];
        }

        UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(145, 160, 100, 20)];
        [button setTitle:@"其他登录方式" forState:UIControlStateNormal];
        [button setTitleColor:[UIColor colorWithRed:74.0/225.0 green:169.0/255.0 blue:1 alpha:1] forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:12];
        [button addTarget:self action:@selector(showMoreViewController) forControlEvents:UIControlEventTouchUpInside];
        [customAreaView addSubview:button];
        [[OpenSDK_UIManager getInstance] handleOtherLoginTypesWithButton:button curLoginType:OpenSDK_S_ONE_KEY];
    }];
}

- (void)back {
    // 返回
    [JVERIFICATIONService dismissLoginControllerAnimated:NO completion:^{
        if (self.actionBlock) {
            self.actionBlock(19909, @"取消登录");
        }
    }];
}

- (void)close {
    // 返回
    [JVERIFICATIONService dismissLoginControllerAnimated:NO completion:^{
        if (self.actionBlock) {
            self.actionBlock(19902, @"取消登录");
        }
    }];
}

- (void)showMoreViewController {
    // 跳转到更多登录界面
    __weak typeof(self) weakSelf = self;
    [JVERIFICATIONService dismissLoginControllerAnimated:NO completion:^{
        __strong typeof(weakSelf) strongSelf = weakSelf;
        if (strongSelf.actionBlock) {
//            BOOL privacyState = strongSelf.uiConfig.privacyState;
//            [[OpenSDK_DataManager getInstance] setContranctChecked:privacyState];
            strongSelf.actionBlock(666, @"其他登录方式");
        }
        //[[OpenSDK_UIManager getInstance] showViewControllerWithSBId:@"LoginMain" vcid:@"OpenSDK_LoginMoreView"];
    }];
}

- (NSString *)simpleContractUrl:(NSString *)url {
    if (!url) { return nil; }
    if ([url containsString:@"?"]) {
        return [url stringByAppendingString:@"&simple=1"];
    } else {
        return [url stringByAppendingString:@"?simple=1"];
    }
}


@synthesize loginDelegate;
@synthesize actionBlock;

@end
